package com.work.zhuanti.bfs;

import com.work.daily.D8_BinaryTreePaths_257_01;

import java.util.LinkedList;
import java.util.Queue;

/**
 * title : 填充每个节点的下一个右侧节点指针
 * link : https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
 * Created by suk on 2020/9/7.
 */
public class T116_Connect_01 {

    public Node connect(Node root) {

        if (root == null)
            return root;

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();

                // 此处参考了答案.如何将指针指向的问题
                if (i < size - 1) {
                    node.next = queue.peek();
                }

                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return root;

    }

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
}
